package com.cskaoyan.javase.array._4operator._3retrieve;

/**
 * @description: 查找数组元素
 * @author: wuguidong@cskaoyan.onaliyun.com
 **/

/**
 * CURD程序员: "增删改查"
 * 增: create
 * 删: delete
 * 改: update
 * 查: retrieve
 *
 * 查找数组元素,如果找到了就返回该元素的下标,如果没找到就返回-1
 *
 *
 */
public class Demo {
    public static void main(String[] args) {
        int[] arr = {12, 3, 324, 32, 4, 34543, 5, 43, 534, 5, 23, 4, 23, 423, 4, 32, 4, 324, 32, 4, 2, 4, 2};
        System.out.println(retrieveLastTargetElementByArray(arr, 4));
        System.out.println(retrieveFirstTargetElementByArray(arr, 4));
    }

    //查找目标元素最后一次出现的下标
    public static int retrieveLastTargetElementByArray(int[] arr, int target) {
        //遍历数组,逐一比对
        //先声明一个目标元素的下标的值
        int targetIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            if (target == arr[i]) {
                targetIndex = i;
            }
        }
        return targetIndex;
    }
    //查找目标元素第一次出现的下标
    public static int retrieveFirstTargetElementByArray(int[] arr, int target) {
        //遍历数组,逐一比对
        //先声明一个目标元素的下标的值
        int targetIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            if (target == arr[i]) {
                targetIndex = i;
                break;
            }
        }
        return targetIndex;
    }
}
